<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  getUserList,
  addUser,
  updateUser,
  deleteUser,
} from '#/api/core/userlist';
import { addcar } from '#/api/core/car';
import type { VbenFormProps } from '@vben/common-ui';
import {
  ElSwitch,
  ElButton,
  ElMessage,
  ElTag,
  ElMessageBox,
} from 'element-plus';
import { useVbenForm, z } from '#/adapter/form';
import { useVbenDrawer } from '@vben/common-ui';
import { ref } from 'vue';

const [Drawer, drawerApi] = useVbenDrawer({
  title: '添加用户',
  footer: false,
});
const [Draweredit, drawereditApi] = useVbenDrawer({
  title: '编辑用户',
  footer: false,
});
const [Drawecar, drawercarApi] = useVbenDrawer({
  title: '绑定车辆',
  footer: false,
});

// const [Modal, modalApi] = useVbenModal({
//   // 连接抽离的组件
//   connectedComponent: carmodel,
// });

interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

const sleep = (time = 1000) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

/**
 * 获取示例表格数据
 */
async function getExampleTableApi(params: {
  Username: string;
  size: number;
  page: number;
}) {
  return new Promise<{ items: any; total: number }>(async (resolve) => {
    const { Username, size, page } = params;
    const items = await getUserList({
      size,
      page,
      Username,
    });
    sleep(200).then(() => {
      resolve({
        total: items.data.total,
        items: items.data.list,
      });
    });
  });
}

const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  pagerConfig: {
    pageSizes: [1, 20, 50],
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { align: 'left', title: '用户名', field: 'username', width: 100 },
    { field: 'email', title: '邮箱' },
    { field: 'role', title: '权限', slots: { default: 'role' } },
    { field: 'phone', title: '电话' },
    { field: 'balance', title: '余额' },
    { field: 'points', title: '积分' },
    { field: 'carWash', title: '洗车卡' },
    { field: 'car', title: '车辆' },

    {
      field: 'createdAt',
      formatter: 'formatDateTime',
      title: '创建时间',
      sortable: true,
    },
    {
      field: 'updatedAt',
      formatter: 'formatDateTime',
      title: '更新时间',
      sortable: true,
    },
    {
      field: 'action',
      fixed: 'right',
      width: 180,
      slots: { default: 'action' },
      title: '操作',
    },
  ],
  exportConfig: {},
  // height: 'auto', // 如果设置为 auto，则必须确保存在父节点且不允许存在相邻元素，否则会出现高度闪动问题
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await getExampleTableApi({
          page: page.currentPage,
          size: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  toolbarConfig: {
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '输入用户名',
      },
      defaultValue: '',
      fieldName: 'Username',
      label: '用户名',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

function open() {
  // @ts-ignore
  formApi.state.type = 1;
  //@ts-ignore
  formApi.state.schema[0].disabled = false;
  drawerApi.open();
}

let editData = ref({});
let caruid = ref({
  id: 0,
});
function openedit(data: {}) {
  //@ts-ignore
  formApi.state.type = 2;
  //@ts-ignore
  formApi.state.schema[0].disabled = true;

  editData.value = data;
  formApi.setValues(editData.value);
  drawereditApi.open();
}

const opencar = (data: any) => {
  caruid.value = data;
  drawercarApi.open();
};
//用户
const [Form, formApi] = useVbenForm({
  //@ts-ignore
  type: 1,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入用户名',
      },
      // 字段名
      fieldName: 'username',
      disabled: false,
      // 界面显示的label
      label: '用户名',
      rules: 'required',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入邮箱',
      },
      // 字段名
      fieldName: 'email',
      // 界面显示的label
      label: '邮箱',
      rules: z.string().email('请输入正确的邮箱'),
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入手机号',
      },
      // 字段名
      fieldName: 'phone',
      // 界面显示的label
      label: '手机号',
      rules: z.string().min(11, { message: '请输入正确的手机号' }),
    },
    {
      component: 'VbenInputPassword',
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'password',
      label: '密码',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入余额',
      },
      fieldName: 'balance',
      defaultValue: 0,
      label: '余额',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入积分',
      },
      fieldName: 'points',
      defaultValue: 0,
      label: '积分',
    },
    {
      component: 'InputNumber',
      componentProps: {
        placeholder: '请输入洗车卡次数',
      },
      fieldName: 'carWash',
      defaultValue: 0,
      label: '洗车卡次数',
    },

    {
      component: 'VbenSelect',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: [
          {
            label: '管理员',
            value: 1,
          },
          {
            label: '业务员',
            value: 2,
          },
          {
            label: '用户',
            value: 3,
          },
        ],
        placeholder: '请选择权限',
        showSearch: true,
      },
      defaultValue: '3',
      fieldName: 'role',
      label: '权限',
      rules: 'selectRequired',
    },
  ],
  wrapperClass: 'grid-cols-1',
});
//车辆
const [Formcar] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmitcar,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车主',
      },
      // 字段名
      fieldName: 'CarOwner',
      disabled: false,
      // 界面显示的label
      label: '车主姓名',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车牌',
      },
      rules: 'required',
      // 字段名
      fieldName: 'CarPlate',
      // 界面显示的label
      label: '车牌号',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车型',
      },
      rules: 'required',
      // 字段名
      fieldName: 'carName',
      // 界面显示的label
      label: '车型',
    },
    {
      // 组件需要在 #/adapter.ts内注册，并加上类型
      component: 'VbenInput',
      // 对应组件的参数
      componentProps: {
        placeholder: '请输入车辆品牌',
      },
      rules: 'required',
      // 字段名
      fieldName: 'CarType',
      // 界面显示的label
      label: '车辆品牌',
    },
  ],
  wrapperClass: 'grid-cols-1',
});
function onSubmit(values: Record<string, any>) {
  values.balance = String(values.balance);
  let url;
  let str;
  let api;
  //@ts-ignore
  if (formApi.state.type == 1) {
    url = addUser;
    str = '添加';
    api = drawerApi;
  } else {
    url = updateUser;
    //@ts-ignore
    values.id = editData.value.id;
    str = '修改';
    api = drawereditApi;
  }

  url(values).then(() => {
    api.close();
    gridApi.query();
    ElMessage.success(str + '成功');
  });
}

function onSubmitcar(values: Record<string, any>) {
  let obj = {
    uid: caruid.value.id,
    CarOwner: values.CarOwner,
    CarPlate: values.CarPlate,
    carName: values.carName,
    CarType: values.CarType,
  };
  addcar(obj).then(() => {
    gridApi.query();
    ElMessage.success('添加成功');
    drawercarApi.close();
  });
}

const del = (data: { id: number }) => {
  ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteUser(data.id).then(() => {
      ElMessage.success('删除成功');
      gridApi.query();
    });
  });
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #status="{ row }">
        <el-switch
          v-model="row.status"
          :active-value="1"
          :inactive-value="2"
          disabled
        />
      </template>

      <template #role="{ row }">
        <el-tag v-if="row.role == '1'" type="danger">管理员</el-tag>
        <el-tag v-else-if="row.role == '3'" type="success">用户</el-tag>
        <el-tag v-else-if="row.role == '2'" type="warning">业务员</el-tag>
      </template>

      <template #action="{ row }">
        <el-button link type="primary" @click="opencar(row)"
          >绑定车辆</el-button
        >
        <el-button link type="primary" @click="openedit(row)">编辑</el-button>
        <el-button link type="danger" @click="del(row)">删除</el-button>
      </template>
      <template #toolbar-tools>
        <el-button class="mr-2" type="primary" @click="open">
          添加用户
        </el-button>
      </template>
    </Grid>
    <Drawer class="w-[800px]" ref="drawer"><Form /> </Drawer>
    <Draweredit class="w-[800px]" ref="draweredit"><Form /> </Draweredit>
    <Drawecar class="w-[800px]" ref="drawercar"><Formcar /> </Drawecar>

    <Modal />
  </div>
</template>
